package org.adream.account.service;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.adream.account.dao.LoginDao;
import org.adream.account.dao.SchoolDao;
import org.adream.account.dao.UserDao;
import org.adream.account.dao.UserRoleLinkDao;
import org.adream.account.dao.UserVerifyDao;
import org.adream.account.entity.SchoolEntity;
import org.adream.account.entity.UserEntity;
import org.adream.account.entity.UserVerifyEntity;
import org.adream.account.model.LoginModel;
import org.adream.account.model.ResultModel;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.restful.vo.SchoolVO;
import org.adream.account.service.async.SynDream2020Service;
import org.adream.account.util.Constant;
import org.adream.account.util.IdGenerator;
import org.adream.account.util.PasswordUtil;
import org.adream.account.util.SDKTestSendTemplateSMS;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SchoolService {
	
	private static final Logger logger = LoggerFactory.getLogger(SchoolService.class);
	
	@Autowired
	private SchoolDao schoolDao;
	
	@Autowired
	private HttpSession session;
	
	@Autowired
	private UserRoleLinkDao userRoleDao;
	
	@Autowired
	private ValidateService validateService;
	
	@Autowired
	private SynDream2020Service synDream2020Service;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private LoginDao loginDao;
	
	@Autowired
	private UserRoleLinkDao userRoleLinkDao;
	
	@Autowired
	private UserVerifyDao verifyDao;
	
	/**
	 * 增
	 * @param school
	 */
	public ResultModel<String> addSchool(SchoolEntity schoolEntity) {
		//生成授权码 并发送
		schoolEntity.setAuthorizationCode(Utils.getAuthorizationCode());
		//短信发送 目前模板是 验证码  暂废弃
//		SDKTestSendTemplateSMS.instance.sendMSMinfoNoCheck(schoolEntity.getPhone(),schoolEntity.getAuthorizationCode());
		schoolEntity.setDirectorNum(0);
		schoolEntity.setCreator("DW");
		schoolEntity.setModifier("DW");
		schoolEntity.setDr(Constant.ONE);
		int result = schoolDao.addSchool(schoolEntity);
		if(result == Constant.ZERO) {
			logger.warn("添加学校失败");
			return new ResultModel<String>(ResultModel.ERR_SERVICE, "操作失败", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 新增或更新学校
	 * @param schoolEntity
	 * @return
	 * @throws ADreamServiceException
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<?> addOrUpdateSchool(SchoolEntity schoolEntity) throws ADreamServiceException {
		//1.先根据sid查询更新
		SchoolEntity school = schoolDao.querySchoolBySid(schoolEntity.getSid());
		if(school != null) {
			Utils.copyPropertiesIgnoreNull(schoolEntity, school);
			schoolEntity.setModifier("DW");
			//更新学校信息
			int result = schoolDao.updateSchool(school);
			if(result == Constant.ZERO) {
				logger.warn("更新学校失败,数据库错误:(");
				return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误0114,请联系系统管理员", null);
			}
			//判断学校是否已删除
			if(schoolEntity.getDr() == Constant.ZERO) {
				//删除学校对应账号uid-梦想中心学校角色关联
				userRoleLinkDao.deleteUserRole(school.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
			} else {
				if(!StringUtils.isEmpty(school.getUid())) {
					userRoleDao.replaceUserRoleById(school.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
					//更新学校账号昵称字段
					userDao.updateSexAndUsernameByUid(school.getUid(), schoolEntity.getSname(), null);
				}
			}
			return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
		} else {
			//2.再根据email查询更新,更改了sid
			List<SchoolEntity> emailSchools = schoolDao.querySchoolsByEmailAndDr(schoolEntity.getEmail(), Constant.ONE);
			if(!Utils.isEmptyCollection(emailSchools)) {
				if(emailSchools.size() > 1) {
					logger.warn("更新学校失败,email:" + schoolEntity.getEmail() + "对应多个学校:(");
					return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败0114-1,邮箱对应多个学校", null);
				}
				SchoolEntity emailSchool = emailSchools.get(0);
				String oriSid = emailSchool.getSid();
				Utils.copyPropertiesIgnoreNull(schoolEntity, emailSchool);
				emailSchool.setModifier("DW");
				int result = schoolDao.updateSchoolByOriSid(emailSchool, oriSid);
				if(result == Constant.ZERO) {
					logger.warn("更新学校失败,数据库错误:(");
					return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误0114-2,请联系系统管理员", null);
				}
				//更新认证表中的sid字段信息
				verifyDao.updateSidVerifiesByOriSid(emailSchool.getSid(), oriSid);
				//判断学校是否已删除
				if(schoolEntity.getDr() == Constant.ZERO) {
					//删除学校对应账号uid-梦想中心学校角色关联
					userRoleLinkDao.deleteUserRole(emailSchool.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
				} else {
					if(!StringUtils.isEmpty(emailSchool.getUid())) {
						userRoleDao.replaceUserRoleById(emailSchool.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
						//更新学校账号昵称字段
						userDao.updateSexAndUsernameByUid(emailSchool.getUid(), schoolEntity.getSname(), null);
					}
				}
				return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
			} else {
				//3.再根据sname查询更新,更改了sid
				List<SchoolEntity> snameSchools = schoolDao.querySchoolsBySnameAndDr(schoolEntity.getSname(), Constant.ONE);
				if(!Utils.isEmptyCollection(snameSchools)) {
					if(snameSchools.size() > 1) {						
						logger.warn("更新学校失败,sname:" + schoolEntity.getSname() + "对应多个学校:(");
						return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败,存在多个同名学校", null);
					}
					SchoolEntity snameSchool = snameSchools.get(0);
					String oriSid = snameSchool.getSid();
					Utils.copyPropertiesIgnoreNull(schoolEntity, snameSchool);
					snameSchool.setModifier("DW");
					int result = schoolDao.updateSchoolByOriSid(snameSchool, oriSid);
					if(result == Constant.ZERO) {
						logger.warn("更新学校失败,数据库错误:(");
						return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误0114-3,请联系系统管理员", null);
					}
					//更新认证表中的sid字段信息
					verifyDao.updateSidVerifiesByOriSid(snameSchool.getSid(), oriSid);
					//判断学校是否已删除
					if(schoolEntity.getDr() == Constant.ZERO) {
						//删除学校对应账号uid-梦想中心学校角色关联
						userRoleLinkDao.deleteUserRole(snameSchool.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
					} else {
						if(!StringUtils.isEmpty(snameSchool.getUid())) {
							userRoleDao.replaceUserRoleById(snameSchool.getUid(), Constant.DREAM_SCHOOL_ROLE_ID);
							//更新学校账号昵称字段
							userDao.updateSexAndUsernameByUid(snameSchool.getUid(), schoolEntity.getSname(), null);
						}
					}
					return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
				} else {
					//4.根据sid,email,sname未查询到相应的学校数据,即是新学校
					UserEntity user = userDao.queryUserByEmail(schoolEntity.getEmail());
					if(user != null) {
						//设置学校账号uid
						schoolEntity.setUid(user.getUid());
					} else {
						//添加学校账号
						user = new UserEntity();
						String uid = IdGenerator.getGuid();
						schoolEntity.setUid(uid);
						user.setUid(uid);
						user.setUname(schoolEntity.getSname());
						user.setEmail(schoolEntity.getEmail());
						user.setCts(new Date());
						user.setCreator("DW");
						user.setMts(new Date());
						user.setModifier("DW");
						user.setDr(Constant.ONE);
						user.setProvince(schoolEntity.getProvince());
						user.setCity(schoolEntity.getCity());
						user.setArea(schoolEntity.getArea());
						user.setRealName(schoolEntity.getSname());
						int addUserResult = userDao.addUser(user);
						if(addUserResult == Constant.ZERO) {
							logger.warn("添加学校账号失败");
							throw new ADreamServiceException("添加学校账号失败");
						}
						//添加学校账号 梦想中心角色
						userRoleLinkDao.replaceUserRoleById(uid, Constant.DREAM_SCHOOL_ROLE_ID);
						//添加学校认证信息
						UserVerifyEntity uvm = new UserVerifyEntity();
						uvm.setUid(uid);
						uvm.setSid(schoolEntity.getSid());
						uvm.setCompany(schoolEntity.getSname());
						uvm.setDr(1);
						uvm.setEmail(schoolEntity.getEmail());
						uvm.setRleId("20181529574197910125");
						uvm.setSort(21);
						uvm.setState(2);
						verifyDao.addUserVerify(uvm);
						
						//添加学校账号 邮箱登录信息
						LoginModel login = new LoginModel();
						login.setUid(uid);
						String salt = Utils.getSixUuid();
						login.setSalt(salt);
						login.setPassword(PasswordUtil.generate(schoolEntity.getSid(), salt));
						login.setLogin(schoolEntity.getEmail());
						login.setMethod(Constant.APWD);
						loginDao.replaceLogin(login);
					}
					schoolEntity.setCreator("DW");
					schoolEntity.setCts(new Date());
					schoolEntity.setModifier("DW");
					schoolEntity.setMts(new Date());
					int result = schoolDao.addSchool(schoolEntity);
					if(result == Constant.ZERO) {
						logger.warn("添加学校失败");
						throw new ADreamServiceException("添加学校失败:(");
					}
					return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
				}
			}
		}
	}
	
	/**
	 * 删
	 * @param sid
	 */
	public ResultModel<String> deleteSchool(String sid) {
		SchoolEntity school = schoolDao.querySchoolBySidAndDr(sid, Constant.ONE);
		if(school == null) {
			logger.warn("删除学校失败,数据不存在sid:{}", sid);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		}
		school.setModifier((String) session.getAttribute("uid"));
		school.setDr(Constant.ZERO);
		int result = schoolDao.deleteSchool(school);
		if(result == 0) {
			logger.warn("删除学校数据失败,数据库错误,sid:{}", sid);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 改
	 * @param sid
	 * @param schoolEntity
	 */
	public ResultModel<String> updateSchool(String sid,SchoolEntity schoolEntity) {
		SchoolEntity school = schoolDao.querySchoolBySidAndDr(sid, Constant.ONE);
		if(school == null) {
			logger.warn("删除学校失败,数据不存在sid:{}", sid);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		}
		Utils.copyPropertiesIgnoreNull(schoolEntity, school);
		school.setModifier((String) session.getAttribute("uid"));
		int result = schoolDao.updateSchool(school);
		if(result == 0) {
			logger.warn("更新学校数据失败,数据库错误,sid:{}", sid);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 根据删除标志查询
	 * @param dr	删除标志
	 * @return
	 */
	public List<SchoolEntity> querySchoolsByDr(Integer dr) {
		return schoolDao.querySchoolsByDr(dr);
	}
	
	/**
	 * 根据sid、删除标志查询
	 * @param sid
	 * @param dr	删除标志
	 * @return
	 */
	public SchoolEntity querySchoolSidAndDr(String sid, Integer dr) {
		return schoolDao.querySchoolBySidAndDr(sid, dr);
	}
	
	/**
	 * 根据%sname%、删除标志分页查询
	 * @param sname		%sname%
	 * @param dr		删除标志
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public PageInfo<SchoolEntity> querySchoolsBySomeFields(String sid,String sname,String schoolType,Integer dr, Integer pageNo,Integer pageSize) {
		pageNo = (pageNo == null) ? Constant.ONE : pageNo;
		pageSize = (pageSize == null) ? Constant.TEN : pageSize;
		PageHelper.startPage(pageNo,pageSize);
		List<SchoolEntity> schools = schoolDao.querySchoolsBySomeFields(sid,sname,schoolType, dr);
		PageInfo<SchoolEntity> page = new PageInfo<>(schools,Constant.TEN);
		return page;
	}
	
	/**
	 * 重置学校梦想主任
	 * @param sid
	 * @param uid
	 * @return
	 * @throws ADreamServiceException 
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<?> resetDirector(String sid, String uid, HttpServletRequest request) throws ADreamServiceException {
		SchoolEntity school = schoolDao.querySchoolBySidAndDr(sid, Constant.ONE);
		if(school == null) {
			logger.warn("重置失败,不存在相应的学校:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "重置失败,未查询到相应数据", null);
		}
		//验证手机号/邮箱合法性
		if(!Utils.verifyPhone(school.getPhone()) && !Utils.verifyEmail(school.getEmail())) {
			logger.warn("重置失败,需要重新发送授权码的手机号和邮箱无效:(");
			return new ResultModel<String>(ResultModel.WARN_PHONE_EMAIL, ResultModel.WARN_PHONE_EMAIL_MSG, null);
		}
		String oriUid = school.getUid();
		
		//重新生成授权码,发送给校长
		String authorizationCode = Utils.getAuthorizationCode();
		school.setAuthorizationCode(authorizationCode);
		school.setDirectorNum(Constant.ZERO);
		school.setUid(null);
		schoolDao.updateDirector(school);
		
		//重新发送授权码
		if(Utils.verifyPhone(school.getPhone())) {
			SDKTestSendTemplateSMS.instance.sendMSMinfoNoCheck(school.getPhone(),authorizationCode);
		}
		
		if(Utils.verifyEmail(school.getEmail())) {
			validateService.sendAuthorizationCodeByEmail(school.getEmail(), authorizationCode, request);
		}
		
		//删除user-role
		userRoleDao.deleteUserRole(uid, Constant.DREAM_DIRECTOR_ROLE_ID);
		
		//同步数据
		SynDream2020DataModel data = new SynDream2020DataModel();
		data.setCasid(oriUid);
		data.setIsDreamDirector(false);
		synDream2020Service.synDream2020Data(data);
		return new ResultModel<String>(ResultModel.SUCCESS, "重置成功", null);
	}
	
	/**
	 * 查询学校信息,包括梦想中心主任
	 * @param suid	学校账号uid
	 * @param state	梦想教师认证状态
	 * @param dr	删除标志
	 * @return
	 */
	public ResultModel<SchoolEntity> querySchoolInfo(String suid, int state, int dr) {
		SchoolEntity school = schoolDao.querySchoolByUidAndDr(suid, dr);
		if(school == null) {
			logger.warn("学校数据不存在:(");
			return new ResultModel<SchoolEntity>(ResultModel.NOT_FOUND_OBJECT, "学校数据不存在", null);
		}
		//查询学校梦想中心主任
		List<UserEntity> directors = userDao.queryTeacherUsersBySuidAndStateAndRleIdAndDr(suid, state, Constant.DREAM_DIRECTOR_ROLE_ID, dr);		
		if(!Utils.isEmptyCollection(directors)) {
			//直接取第一个
			school.setDirector(directors.get(0));
		}
		return new ResultModel<SchoolEntity>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, school);
	}
	
	/**
	 * 查询学校梦想教师
	 * @param suid	学校账号uid
	 * @param state	梦想教师认证状态
	 * @param dr	删除标志
	 * @return
	 */
	public ResultModel<List<UserEntity>> querySchoolTeachers(String suid, int state, int dr) {
		List<UserEntity> schoolTeachers = userDao.queryTeacherUsersBySuidAndStateAndDr(suid, state, dr);
		if(Utils.isEmptyCollection(schoolTeachers)) {
			logger.warn("学校还没有梦想教师:(");
			return new ResultModel<List<UserEntity>>(ResultModel.NOT_FOUND_OBJECT, "数据不存在", null);
		}
		return new ResultModel<List<UserEntity>>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, schoolTeachers);
	}
	
	/**
	 * 重新绑定梦想中心主任
	 * @param suid	学校账号uid
	 * @param sid	学校id
	 * @param duid	需重新绑定的梦想中心主任uid
	 * @param state	认证状态
	 * @param dr	删除标志
	 * @return
	 */
	public ResultModel<?> reBindDirector(String suid, String sid, String duid, int state, int dr) {
		if(!StringUtils.isEmpty(duid)) {			
			UserEntity director = userDao.queryTeacherUserBySuidAndUidAndStateAndDr(suid, duid, state, dr);
			if(director == null) {
				logger.warn("该用户梦想教师认证未通过或不隶属于该学校:(");
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "重新绑定失败,请刷新重试", null);
			}
			List<UserEntity> directors = userDao.queryTeacherUsersBySuidAndStateAndRleIdAndDr(suid, state, Constant.DREAM_DIRECTOR_ROLE_ID, dr);
			//若已存在梦想中心主任,去除相应的用户角色
			if(!Utils.isEmptyCollection(directors)) {
				directors.forEach(d -> {
					userRoleLinkDao.deleteUserRole(d.getUid(), Constant.DREAM_DIRECTOR_ROLE_ID);
				});
			}
			int result = userRoleLinkDao.replaceUserRoleById(duid, Constant.DREAM_DIRECTOR_ROLE_ID);
			if(result == Constant.ZERO) {
				logger.warn("重新绑定梦想中心主任失败,数据库错误:(");
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误411,请联系管理员", null);
			}
			//查询梦想中心主任梦想教师认证数据
			UserVerifyEntity schoolVerify = verifyDao.queryVerifyByUidAndRleIdAndDr(duid, Constant.TEACHER_ROLE_ID, Constant.ONE);
			//同步新版盒子数据
			SynDream2020DataModel data = new SynDream2020DataModel();
			data.setCasid(duid);
			data.setSchoolNumber(sid);
			data.setIsTeacher(true);
			data.setIsDreamDirector(true);
			data.setCreateTime(schoolVerify != null ? schoolVerify.getCts().getTime() / 1000 : null);
			synDream2020Service.synDream2020Data(data);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 根据uid 查询 梦想教师认证 成功  后 关联的学校
	 * @param uid
	 * @return
	 */
	public SchoolEntity queryMySchoolByUid(String uid) {
		if(StringUtils.isEmpty(uid)||StringUtils.isEmpty(uid.trim())) {
			return null;
		}
		SchoolEntity schoolEntity = schoolDao.queryMySchoolByUid(uid.trim());
		return schoolEntity;
	}
	
	/**
	 * 	在调用前 请验证 position 和 count 此处不验证
	 * @param position
	 * @param count
	 * @return
	 */
	public List<SchoolVO> querySchoolsInfo(Integer position, Integer count,String time) {
		return schoolDao.querySchoolsInfo(position,count,time);
	}
}